/*
 * @(#) MenuServiceImpl.java 2018年1月25日 上午10:53:51
 *
 * Copyright 2018 CIMIP, Inc. All rights reserved.
 * H-VISIONS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */package cn.hc.share.service.impl;

import java.sql.Timestamp;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.aspectj.apache.bcel.generic.NEWARRAY;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hc.share.dao.ArticleAndTagDao;
import cn.hc.share.dao.TagDao;
import cn.hc.share.dao.UserDao;
import cn.hc.share.entity.ArticleAndTag;
import cn.hc.share.entity.Tag;
import cn.hc.share.entity.User;
import cn.hc.share.service.ArticleAndTagSaveException;
import cn.hc.share.service.TagSaveException;
import cn.hc.share.service.TagService;
import cn.hc.share.service.UserNotFoundException;
import cn.hc.share.util.StringUtil;

@Service("tagService")
public class TagServiceImpl2 implements TagService
{

	@Resource
	private TagDao tagDao;

	@Resource
	private ArticleAndTagDao articleAndTagDao;

	@Resource
	private UserDao userDao;

	// 新增一个标签
	@Transactional
	public Tag saveTag(Tag tag)
	{
		if (tag == null)
		{
			throw new RuntimeException("标签信息不存在!");
		}
		int num = tagDao.addTag(tag);
		if (num != 1)
		{
			throw new TagSaveException("标签保存失败!");
		}
		return tag;
	}

	// 新增标签
	@Transactional
	public String addTags(String tagNames, String builder, String articleId)
	{

		String tagIdsForArticle = "";
		if (StringUtil.isNotNull(tagNames))
		{
			String[] tags = tagNames.split(",");
			for (String tag : tags)
			{
				try
				{
					tag = tag.trim();
					Tag tagForSearch = new Tag();
					tagForSearch.setName(tag);
					tagForSearch.setBuilder(builder);

					// 如果存在标签,不再新增标签
					List<Tag> findTag = tagDao.findTag(tagForSearch);

					if (findTag.size() > 0)
					{
						tagIdsForArticle += findTag.get(0).getId() + ",";
						// 增加文章标签关联数据
						int num = addArticleAndTagForArticle(articleId, builder, findTag.get(0).getId());
						if (num != 1)
						{
							throw new ArticleAndTagSaveException("文章增加书签失败!");
						}

					} else // 不存在
					{

						String id = UUID.randomUUID().toString();
						Timestamp createTime = new Timestamp(System.currentTimeMillis());

						Tag tagAdd = new Tag();
						tagAdd.setId(id);
						tagAdd.setBuilder(builder);
						tagAdd.setCreateTime(createTime);
						tagAdd.setName(tag);

						int addTag = tagDao.addTag(tagAdd);
						if (addTag != 1)
						{
							System.out.println("保存标签:" + tag + "失败!");
						}
						tagIdsForArticle += id + ",";

						// 增加文章标签关联数据
						int num = addArticleAndTagForArticle(articleId, builder, id);
						if (num != 1)
						{
							System.out.println("文章增加'" + tag + "'书签失败!");
						}
					}
				} catch (Exception e)
				{
					continue;
				}
			}
			if (StringUtil.isNotNull(tagIdsForArticle))
			{
				tagIdsForArticle = tagIdsForArticle.substring(0, tagIdsForArticle.length() - 1);
			}
		}
		return tagIdsForArticle;
	}

	// 增加标签关联数据
	@Transactional
	public int addArticleAndTagForArticle(String articleId, String userId, String tagId)
	{

		ArticleAndTag tag = articleAndTagDao.findTagByArticleTagUser(articleId, userId, tagId);

		if (tag != null)
		{
			return 1;
		}

		ArticleAndTag articleAndTag = new ArticleAndTag();

		String id = UUID.randomUUID().toString();
		Timestamp createTime = new Timestamp(System.currentTimeMillis());

		articleAndTag.setId(id);
		articleAndTag.setArticleId(articleId);
		articleAndTag.setCreateTime(createTime);
		articleAndTag.setTagId(tagId);
		articleAndTag.setUserId(userId);

		int num = articleAndTagDao.addArticleAndTag(articleAndTag);

		return num;
	}

	// 获取用户创建的标签
	public List<Tag> getTagsByUserId(String userId)
	{
		List<Tag> tags = null;
		if (StringUtil.isNotNull(userId))
		{
			User user = userDao.findUserById(userId);
			if (user == null)
			{
				throw new UserNotFoundException("用户不存在!");
			}
			Tag tag = new Tag();
			tag.setBuilder(userId);
			tags = tagDao.findTag(tag);
		}
		return tags;
	}

	// 更新标签
	@Transactional
	public int updateTag(String tagId, String tagNewName, String type)
	{
		int num = 0;
		if ("RENAME".equals(type))
		{
			Tag tag = new Tag();
			tag.setId(tagId);

			List<Tag> list = tagDao.findTag(tag);
			if (list.size() > 0)
			{
				Tag tag2 = list.get(0);
				tag2.setName(tagNewName);
				num = tagDao.updateTag(tag2);
				if (num != 1)
				{
					throw new TagSaveException("标签修改名称失败!");
				}
			}
		}
		if ("DELETE".equals(type))
		{

		}
		return num;
	}

	// 新增标签
	@Transactional
	public String addNewTag(String tagNames, String builder)
	{

		String addNewTag = "";
		String oldTag = "";
		String tagIdsForArticle = "";
		if (StringUtil.isNotNull(tagNames))
		{
			String[] tags = tagNames.split(",");
			for (String tag : tags)
			{
				try
				{
					tag = tag.trim();
					Tag tagForSearch = new Tag();
					tagForSearch.setName(tag);
					tagForSearch.setBuilder(builder);

					// 如果存在,不再新增
					List<Tag> findTag = tagDao.findTag(tagForSearch);

					if (findTag.size() > 0)
					{
						oldTag += tag + ",";
						continue;
					}
					String id = UUID.randomUUID().toString();
					Timestamp createTime = new Timestamp(System.currentTimeMillis());

					Tag tagAdd = new Tag();
					tagAdd.setId(id);
					tagAdd.setBuilder(builder);
					tagAdd.setCreateTime(createTime);
					tagAdd.setName(tag);

					int addTag = tagDao.addTag(tagAdd);
					if (addTag != 1)
					{
						System.out.println("保存标签:" + tag + "失败!");
					}

					addNewTag += tag + ",";

				} catch (Exception e)
				{
					continue;
				}
			}
			if (StringUtil.isNotNull(addNewTag))
			{
				tagIdsForArticle += addNewTag.substring(0, addNewTag.length() - 1);
			}
			if (StringUtil.isNotNull(oldTag))
			{
				if (StringUtil.isNotNull(tagIdsForArticle))
				{
					tagIdsForArticle += ";" + oldTag.substring(0, oldTag.length() - 1);
				}else {
					tagIdsForArticle += oldTag.substring(0, oldTag.length() - 1);
				}
			}

		}
		return tagIdsForArticle;
	}
}
